package com.feng.rabbitmq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class MyCallBack implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnsCallback {

    @Autowired
    RabbitTemplate rabbitTemplate;

    //注入
    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        /**
         * 交换机确认回调方法
         * 1.发消息交换机接收到了回调
         * 1.1 correlationData保存回调消息的ID及相关信息
         * 1.2交换机收到消息ack = true
         * 1.3 cause null
         * 2.发消息交换机接收失败了回调
         * 2.1 correlationData保存回调消息的ID及相关信息
         * 2.2交换机收到消息ack = false
         * 2.3 cause失败的原因
         */
        String id = correlationData!=null?correlationData.getId():"";
        if (ack){
            //交换机已经收到id为1的消息
            log.info("交换机已经收到id为{}的消息",id);
        }else {
            log.info("交换机还没有收到id为{}的消息，是因为：{}",id,cause);
        }
    }

    //只有在不达目的时才回退
    @Override
    public void returnedMessage(ReturnedMessage returned) {
        log.info("消息{}，被交换机{}退回，退回原因是：{}，路由Key: {}",
                returned.getMessage(),
                returned.getExchange(),
                returned.getReplyText(),
                returned.getRoutingKey());
    }
}
